"use strict";
importScripts("psl.min.js","common.js");

var _whiteList = null;

async function getWhiteList() {
	var result = await chrome.storage.local.get("whitelist");
	_whiteList = result.whitelist;
	if (!_whiteList) {
		_whiteList = "^http[s]?://([\\w\\-]+\\.)*gov\\.cn(/.*)?$\n^http[s]?://([\\w\\-]+\\.)*360\\.(cn|net|com)(/.*)?$";
	}
	return _whiteList;
}

async function setWhiteList(data) {
	_whiteList = data;
	return await chrome.storage.local.set({whitelist: data});
}

async function updateBrowserStatus() {
	var c = await getDataCount();
	chrome.action.setTitle({title: "回收站(" + c + ")"});
	chrome.action.setIcon(c > 0 ? {path: "/images/ico54-012.png"} : {path: "/images/ico55-012.png"});
}

async function updateData() {
	await setRootJson(_rootJson);
	await updateBrowserStatus();
	chrome.tabs.query({}, function(tabs) {
		for (var tab of tabs) {
			chrome.tabs.sendMessage(tab.id,{name: "update-data"}).catch(error => {
				showError("update-data", error);
			});
		}
	});
}

function main() {
	chrome.contextMenus.removeAll(function() {
		var myContexts = ["page", "frame", "selection", "link", "editable", "image", "video", "audio"];
		chrome.contextMenus.create({
			title: "回收站",
			id: "recycle-bin",
			documentUrlPatterns: ["http://*/*","https://*/*","file:///*","ftp://*/*","urn:*"],
			contexts: myContexts
		});
		chrome.contextMenus.create({
			title: "移入回收站",
			id: "throw-into-the-recyclebin",
			parentId: "recycle-bin",
			contexts: myContexts
		});
		chrome.contextMenus.create({
			title: "移入全局回收站",
			id: "throw-into-the-global-recyclebin",
			parentId: "recycle-bin",
			contexts: myContexts
		});
		chrome.contextMenus.create({
			title: "移入回收站并举报",
			id: "throw-into-the-recyclebin-and-report",
			parentId: "recycle-bin",
			contexts: myContexts
		});
		chrome.contextMenus.create({
			id: "separator1",
			parentId: "recycle-bin",
			contexts: myContexts,
			type: "separator"
		});
		chrome.contextMenus.create({
			title: "打开选项页面",
			id: "open-options-page",
			parentId: "recycle-bin",
			contexts: myContexts
		});
		chrome.contextMenus.create({
			id: "separator2",
			parentId: "recycle-bin",
			contexts: myContexts,
			type: "separator"
		});
		chrome.contextMenus.create({
			title: "清空回收站",
			id: "clear-all-data",
			parentId: "recycle-bin",
			contexts: myContexts
		});
		chrome.contextMenus.create({
			title: "撤销移入操作",
			id: "pop-item",
			parentId: "recycle-bin",
			contexts: myContexts
		});
		
		chrome.contextMenus.onClicked.addListener(function(info,tab) {
			switch (info.menuItemId) {
			case "open-options-page":
				chrome.runtime.openOptionsPage();
				break;
			default:
				chrome.tabs.sendMessage(tab.id, {name: info.menuItemId}, {frameId: info.frameId}).catch(error => {
					showError(info.menuItemId, error);
				});
				break;
			}
		});
	});

	chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
		//console.log("onMessage: " + message.name);
		(async () => {
			switch (message.name) {
			case "get-data":
				var rj = await getRootJson();
				sendResponse({rootJson: rj});
				break;
			case "set-data":
				_rootJson = message.data;
				await updateData();
				sendResponse();
				break;
			case "clear-all-data":
				var rj = await getRootJson();
				var arrdata = rj.data;
				var i = arrdata.length - 1;
				while (i >= 0) {
					if (!hasOption(arrdata[i],"prevent_delete")) {
						arrdata.splice(i,1);
					}
					i--;
				}
				await updateData();
				chrome.tabs.query({}, function(tabs) {
					for (var tab of tabs) {
						chrome.tabs.sendMessage(tab.id,{name: "clear-data"}).catch(error => {
							showError("clear-data", error);
						});
					}
				});
				sendResponse();
				break;
			case "push-item":
				message.data.page_url = sender.tab.url;

				var wl = await getWhiteList();
				var blnInWhiteList = false;
				for (var pattern of wl.split("\n")) {
					if (pattern == "") {
						continue;
					}
					var objRegExp = new RegExp(pattern,"i");
					if (objRegExp.test(message.data.frame_url) || objRegExp.test(message.data.page_url)) {
						blnInWhiteList = true;
						break;
					}
				}
				if (blnInWhiteList) {
					sendResponse({data: "回收站: 网址在白名单中!"});
				} else {
					var rj = await getRootJson();
					rj.data.push(message.data);
					await updateData();
					chrome.tabs.query({}, function(tabs) {
						for (var tab of tabs) {
							if (!isObjEqual(tab,sender.tab)) {
								chrome.tabs.sendMessage(tab.id,{name: "hide-item", data: message.data}).catch(error => {
									showError("hide-item", error);
								});
							}
						}
					});
					sendResponse({data: message.data});
				}
				break;
			case "pop-item":
				var rj = await getRootJson();
				var arrdata = rj.data;
				var i = arrdata.length - 1;
				while (i >= 0) {
					if (!hasOption(arrdata[i],"prevent_delete")) {
						break;
					}
					i--;
				}
				if (i >= 0) {
					var arr = arrdata.splice(i,1);
					await updateData();
					for (var item of arr) {
						chrome.tabs.query({}, function(tabs) {
							for (var tab of tabs) {
								chrome.tabs.sendMessage(tab.id, {name: "restore-item", data: item}).catch(error => {
									showError("restore-item", error);
								});
							}
						});
					}
				}
				sendResponse({count: arrdata.length});
				break;
			case "get-data-count":
				var c = await getDataCount();
				sendResponse({count: c});
				break;
			case "get-whitelist":
				var wl = await getWhiteList();
				sendResponse({whitelist: wl});
				break;
			case "set-whitelist":
				await setWhiteList(message.whitelist);
				sendResponse();
				break;
			case "capture-page":
				chrome.tabs.captureVisibleTab(null, {format: "png"}, function(data) {
					chrome.storage.local.set({capture: {jsonData: message.data, imageData: data}}, function() {
						chrome.runtime.openOptionsPage();
						sendResponse();
					});
				});
				break;
			}
		})();
		
		return true;
	});

	updateBrowserStatus();
	
	chrome.webNavigation.onDOMContentLoaded.addListener(function(details) {
		if (details.frameId == 0) {
			chrome.tabs.sendMessage(details.tabId, {name: "init-page", data: "回收站: 已加载."}, {frameId: details.frameId}).catch(error => {
				showError("init-page", error);
			});
		}
	}, {url: [{schemes: ["http", "https"]}]});
}

main();
